package com.pic.mgt.haishin.action.shell;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;

import com.pic.mgt.action.MissUnitInspectAction;
import com.pic.mgt.haishin.action.HaishinMessageRecoverAction;
import com.pic.mgt.telnetd.AbstractCommandPerformer;

// (送多方新增)
public class HaishinMessageRecoverCommandPerformer extends
AbstractCommandPerformer {

	private final String commandName = "rcvmsg";
	private final String commandDescritpion = "recovery miss or halt message.";

	private HaishinMessageRecoverAction haishinMessageRecoverAction;

	private MissUnitInspectAction missMessageUnitInspectAction;

	@Override
	protected void addOption(Options options) {
		options.addOption("tn", true, "assign transaction file name to recover. (*MUST SURE MESSAGE WAS MISSED OR HALTED.) (incompatible with 'at')");
		options.addOption("at", false, "auto-inspect miss messages and do recovery. (incompatible with 'tn')");
	}

	@Override
	protected String doCommandPerform(CommandLine commandLine) {
		// 如果同時有 'tn' 和 'at' 的參數,表示語意不明
		if (commandLine.hasOption("tn") && commandLine.hasOption("at")) {
			return
			super.getReplyMessageWithReplyCode("'-tn' and '-at' are incompatible.",
					this.COMMAND_PERFORM_FAILED_CODE);
		}

		// ---------------------------------------

		if (commandLine.hasOption("tn")) {
			boolean isRecoverySuccessful = 
				this.haishinMessageRecoverAction.recoverMessage(
						commandLine.getOptionValue("tn"));

			if (isRecoverySuccessful) {
				return super.getCommandPerformFinishMsg();
			}
			else {
				return super.getCommandPerformFailedMsg();
			}
		}
		else if(commandLine.hasOption("at")) {
			boolean isAutoRecoverySuccessful =
				this.missMessageUnitInspectAction.inspectMissUnitAndRecover();

			if (isAutoRecoverySuccessful) {
				return super.getCommandPerformFinishMsg();
			}
			else {
				return super.getCommandPerformFailedMsg();
			}
		}
		else {
			return
			super.getReplyMessageWithReplyCode("did not provide recovery parameters.",
					this.COMMAND_PERFORM_FAILED_CODE);
		}
	}

	@Override
	public String getCommandDescription() {
		return this.commandDescritpion;
	}

	@Override
	public String getCommandName() {
		return this.commandName;
	}

	public void setHaishinMessageRecoverAction(HaishinMessageRecoverAction haishinMessageRecoverAction) {
		this.haishinMessageRecoverAction = haishinMessageRecoverAction;
	}

	public void setMissMessageUnitInspectAction(
			MissUnitInspectAction missMessageUnitInspectAction) {
		this.missMessageUnitInspectAction = missMessageUnitInspectAction;
	}

}
